from typing import Optional

from appium.webdriver.common.appiumby import AppiumBy
from loguru import logger
from selenium.common import StaleElementReferenceException
from selenium.webdriver.support.wait import WebDriverWait
from base.base_driver import DRIVER


class BasePage:
    def __init__(self):
        self.driver = DRIVER



    def _locator(self, loc, wait: int = None, freq: int = 0.5) -> Optional['WebElement']:
        """
        元素定位
        :param loc: 元素定位元组
        :param wait: 等待时间
        :param freq: 等待频率
        :return: 定位到的元素
        """

        return self.driver.find_element(*loc) if wait is None else \
            WebDriverWait(self.driver, wait, freq, [StaleElementReferenceException]).until(
                lambda x: x.find_element(*loc))


    def _click(self, loc, wait: int = None, freq: int = 0.5):
        if isinstance(loc, str):
            locator = (AppiumBy.ANDROID_UIAUTOMATOR, loc)
        else:
            locator = loc
        logger.info(f"点击元素: {loc}")
        self._locator(locator, wait).click()



